package com.ht.baselibs.exception;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;

import com.ht.baselibs.BuildConfig;
import com.ht.baselibs.utils.SharedPreferencesUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 程序异常抓包
 *
 * @author MarsKang
 *
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {
    public static final String PRE_EXCEPTION_SAVE_TIME = "pre_exception_save_time";
    private static CrashHandler INSTANCE = new CrashHandler();
    private Context mContext;
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    private Map<String, String> Infos = new HashMap<String, String>();
    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return INSTANCE;
    }

    public void init(Context ctx) {
        mContext = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(final Thread thread, final Throwable ex) {
        // TODO Auto-generated method stub
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else { // 如果自己处理了异常，则不会弹出错误对话框，则需要手动退出app
            new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
                    new AlertDialog.Builder(mContext).setTitle("提示")
                            .setCancelable(false).setMessage("程序崩溃了...")
                            .setNeutralButton("我知道了", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    mDefaultHandler.uncaughtException(thread, ex);
                                }
                            }).create().show();
                    Looper.loop();
                }
            }.start();
        }
    }

    /**
     * 自定义错误处理
     */
    private boolean handleException(final Throwable ex) {
        if (ex == null) {
            return true;
        }

        Date currentDate = new Date();
        if (currentDate.getTime() - SharedPreferencesUtils.getLong(PRE_EXCEPTION_SAVE_TIME, 0) > 3000){
            collectDeviceInfo(mContext);
            saveCrashInfo2File(ex);
            android.os.Process.killProcess(android.os.Process.myPid());
        }
        SharedPreferencesUtils.put(PRE_EXCEPTION_SAVE_TIME, currentDate.getTime());
        return true;
    }

    /**
     * 收集设备参数信息
     *
     * @param ctx
     */
    public void collectDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                Infos.put("versionInfo", "版本信息");
                Infos.put("versionName", versionName);
                Infos.put("versionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        Field[] fields = Build.class.getDeclaredFields();
        Infos.put("errorInfo", "异常信息");
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Infos.put(field.getName(), field.get(null).toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void saveCrashInfo2File(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : Infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\r\n");
        }
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = formatter.format(new Date());
            String fileName = "crash-" + time + ".txt";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String path = Environment.getExternalStorageDirectory() +"/."+ BuildConfig.APPLICATION_ID+"/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName);
                fos.write(sb.toString().getBytes());
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
